/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2025. All rights reserved.
 */

import { Input, InputFile, LocalFileWriter, OutputFile } from '@ohos/hvigor';

import { ProjectModelImpl } from '../../model/project/project-model-impl.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';

import CommonTask = TaskNames.CommonTask;
import { getBuildModeName } from '../../utils/task-util.js';
import { OhosLogger } from "../../utils/log/ohos-logger.js";
import { OhosHarTask } from "../task/ohos-har-task.js";
import { normalizedFileData } from "../../utils/build-profile-utils.js";

export interface HarBuildProfileData {
  HAR_VERSION: string;
  BUILD_MODE_NAME: string;
  DEBUG: boolean;
  TARGET_NAME: string;
}

export class HarBuildProfileTask extends OhosHarTask {
  private _log = OhosLogger.getLogger(HarBuildProfileTask.name);
  protected readonly harTaskService: TargetTaskService;
  protected harBuildProfileData: HarBuildProfileData | undefined;

  constructor(taskService: TargetTaskService) {
    super(taskService, CommonTask.CREATE_HAR_BUILD_PROFILE);
    this.harTaskService = taskService;
    this.initDefaultData();
  }

  protected initDefaultData(): void {
    this.harBuildProfileData = {
      HAR_VERSION: this.harVersion,
      BUILD_MODE_NAME: this.buildModeName,
      DEBUG: this.harTaskService.isDebug(),
      TARGET_NAME: this.harTargetName,
    };
  }

  // 增量输入文件-app.json5
  @InputFile() private get appJsonPath(): string {
    return (this.service.getProjectModel() as ProjectModelImpl).getAppRes().getJsonPath();
  }
  // 增量输入文件-build-profile.json5
  @InputFile() private get projectProfilePath(): string {
    return this.projectModel.getProfilePath();
  }
  // 输出产物-BuildProfile.ets
  @OutputFile() private get harBuildProfilePath(): string {
    return this.pathInfo.getHarGenerateBuildProfilePath();
  }

  @Input() private get buildModeName(): string {
    return getBuildModeName();
  }
  @Input() private get buildMode(): string {
    return this.targetService.getBuildMode();
  }
  @Input() private get buildProfileFields(): object | undefined {
    return this.targetService.getBuildProfileFields();
  }
  @Input() private get harVersion(): string {
    return this.packageJsonObj.version;
  }
  @Input() private get harTargetName(): string {
    return this.harTaskService.getTargetData().getTargetName();
  }

  initTaskDepends(): void {}

  protected doTaskAction(): void {
    const buildProfileFields = this.buildProfileFields;
    const buildProfileParams = buildProfileFields ?
      { ...this.harBuildProfileData, ...buildProfileFields } : { ...this.harBuildProfileData };
    LocalFileWriter.getInstance().writeStr(
      this.harBuildProfilePath, normalizedFileData(buildProfileParams, this.targetData, this._log)
    );
  }
}
